import axios from 'axios';
import router from '~/router';
import store from '~/state';
import qs from 'qs';
import { isWeixin } from '~/utils/index.js';

var instance = axios.create();

instance.defaults.timeout = 0;
instance.defaults.baseURL = '/api/';
instance.defaults.headers.common = {
	'X-Requested-With' : 'xmlhttprequest',
};
instance.defaults.headers.post = {
	'Content-Type' : 'application/x-www-form-urlencoded'
};
instance.defaults.validateStatus = function (status) {
	return status >= 200 && status < 300; // default
}
instance.defaults.transformRequest = [function (data) {
	if (data) {
		data = qs.stringify(data);
	}
	return data;
}];

//请求时置为loading状态
instance.interceptors.request.use(function (config) {
	store.commit('loading', true);
	console.log(store.state.loading);

	return config;
});


instance.interceptors.response.use(function (response) {
	store.commit('loading', false);

	return response;
}, function (error) {
	store.commit('loading', false);
	console.log(store.state.loading);

	if (error.response.status == 401) {
		// 未认证
		store.commit('logout');
		if (router.currentRoute.path != '/auth/login') {
			router.push('/auth/login?redirect='+router.currentRoute.fullPath);
			return error.response;
		} else {
			router.push('/auth/login?redirect='+router.currentRoute.query.redirect);
			return error.response;
		}


	} else if (error.response.status == 422) {
		error.message = error.response.data.error_msg;
		return Promise.reject(error);
	} else {
		console.log(error);
		error.message = '网络错误';
		return Promise.reject(error);
	}
});

export default instance;
